package com.future.heatwave

import android.app.Application
import androidx.compose.runtime.mutableStateListOf
import androidx.lifecycle.AndroidViewModel
import androidx.lifecycle.viewModelScope
import com.future.heatwave.db.VideoDatabase
import com.future.heatwave.db.entity.SectionsEntityRecord
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext

class SectionsDataViewModel(application: Application) : AndroidViewModel(application) {
    private val database = VideoDatabase.getDb(application).videoDao()
    private val _items = mutableStateListOf<SectionsEntityRecord>()
    val items: List<SectionsEntityRecord> = _items
    suspend fun getAllItems(): List<SectionsEntityRecord> {
        return database.getAllSections()
    }

    suspend fun getDramaIdAllSections(dramaId:Long): List<SectionsEntityRecord> {
        return database.getDramaIdAllSections(dramaId,false)
    }

    fun insertItem(item: SectionsEntityRecord) {
        viewModelScope.launch {
            // 在 IO 线程执行数据库插入操作
            withContext(Dispatchers.IO) {
                database.insertSections(item)
            }
            // 更新 UI 线程的数据
            _items.add(item)
        }
    }

    fun deleteItem(item: SectionsEntityRecord) {
        viewModelScope.launch {
            // 在 IO 线程执行数据库删除操作
            withContext(Dispatchers.IO) {
                database.deleteSections(item)
            }
            // 更新 UI 线程的数据
            _items.remove(item)
        }
    }
}